﻿using Microsoft.Extensions.DependencyInjection;

namespace StarsAdmin.Core.App
{
    /// <summary>
    /// 全局获取服务
    /// </summary>
    public class AppHelper
    {
        private static IServiceProvider _serviceProvider;

        public static IServiceProvider ServiceProvider
        {
            get => _serviceProvider ?? throw new InvalidOperationException("服务提供商为空.");
        }

        /// <summary>
        /// 设置服务提供者
        /// </summary>
        /// <param name="serviceProvider">服务提供者实例</param>
        public static void SetServiceProvider(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider ?? throw new InvalidOperationException("服务提供商为空.");
        }

        /// <summary>
        /// 获取服务实例
        /// </summary>
        /// <typeparam name="TService">服务类型</typeparam>
        /// <returns>服务实例</returns>
        public static TService GetService<TService>()
        {
            if (ServiceProvider == null)
            {
                throw new InvalidOperationException("服务提供商为空.");
            }
            return ServiceProvider.GetService<TService>();
        }
    }
}